package com.hui.stock.security.service;

import com.hui.stock.face.UserCacheFace;
import com.hui.stock.mapper.SysRoleMapper;
import com.hui.stock.mapper.SysRolePermissionMapper;
import com.hui.stock.mapper.SysUserMapper;
import com.hui.stock.pojo.entity.SysPermission;
import com.hui.stock.pojo.entity.SysUser;
import com.hui.stock.security.user.LoginUserDetail;
import com.hui.stock.utils.UserRolePermissionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: ymh
 * @date: 2025/1/12 14:54
 * @description: 获取认证用户的详情信息bean
 */
@Service("userDetailsService")
public class LoginUserDetailService implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Autowired
    private UserCacheFace userCacheFace;

    /**
     * 根据用户名获取用户详情信息：用户名 密文密码 权限集合
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1 根据用户名调用mapper方法获取用户
        SysUser dbUser = sysUserMapper.findUserInfoByUserName(username);
        if (dbUser==null){
            throw new UsernameNotFoundException("用户不存在！");
        }
        //2 组装UserDetails对象
        //2.1 基本字段：用户名 密码 权限集合等

        //2.2 其他字段：id email phone menus permissions 等
        // //1 获取用户角色id
        // List<Long> roleIds = sysRoleMapper.getRoleIds(dbUser.getId());
        // //2 根据用户角色id获取菜单列表
        // List<SysPermission> permissions = sysRolePermissionMapper.getPermissionList(roleIds);
        // List<MenuDomain> menus = UserRolePermissionUtil.buildPermissionTree(permissions);
        // //按钮
        // List<String> buttonPermissions = new ArrayList<>();
        // // 分类菜单和按钮权限
        // permissions.forEach(permission->{
        //     if (permission.getType()==3){
        //         if (!StringUtils.isBlank(permission.getCode())){
        //             buttonPermissions.add(permission.getCode());
        //         }
        //     }
        // });
        // //获取SpringSecurity的权限标识ROLE_角色名称
        // List<String> pers = permissions.stream()
        //         .map(SysPermission::getPerms)
        //         .filter(StringUtils::isNotBlank)
        //         .collect(Collectors.toList());
        // List<SysRole> sysRoles = sysRoleMapper.batchSelectByPrimaryKey(roleIds);
        // pers.addAll(sysRoles.stream()
        //         .map(per->"ROLE_"+per.getName())
        //         .collect(Collectors.toList()));
        // //将用户拥有的权限列表转为权限对象
        // List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(pers.toArray(new String[pers.size()]));
        List<SysPermission> userPermissions = userCacheFace.getUserPermissions(dbUser.getId());
        // //按钮
        List<String> buttonPermissions = new ArrayList<>();
        // 分类菜单和按钮权限
        userPermissions.forEach(permission->{
            if (permission.getType()==3){
                if (!StringUtils.isBlank(permission.getCode())){
                    buttonPermissions.add(permission.getCode());
                }
            }
        });
        List<String> pers = userCacheFace.getUserGrantedAuthorityString(dbUser.getId());
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(pers.toArray(new String[pers.size()]));
        LoginUserDetail userDetail = new LoginUserDetail();
        BeanUtils.copyProperties(dbUser,userDetail);
        userDetail.setPermissions(buttonPermissions);
        userDetail.setMenus(UserRolePermissionUtil.buildPermissionTree(userPermissions));
        userDetail.setAuthorities(authorityList);
        return userDetail;
    }
}
